import json
from datetime import datetime
from decimal import Decimal
from rest_framework.response import Response
from django.db import transaction
from django.utils import timezone
from rest_framework import serializers, status
from rest_framework.exceptions import ValidationError
from rest_framework.generics import get_object_or_404

from home.models import Commodity, ProductCategory, DishCategory, Product, Dish, Unit, Inventory, DishProduct, \
    SalesRecord
from user.models import Team


class UnitSerializer(serializers.Serializer):
    # 序列化某些字段，这里写要序列化的字典
    id = serializers.ReadOnlyField(source='unit_id')
    name = serializers.CharField()  # serializers下大致跟models下的类是对应的
    unit_type = serializers.IntegerField()
    conversion_relation = serializers.CharField()
    is_dish_unit = serializers.BooleanField()

    def create(self, validated_data):
        # 保存的逻辑
        # validated_data 校验过后的数据 {name,price,publish}
        # 保存到数据库
        unit = Unit.objects.create(**validated_data)
        # 一定不要返回新增的对象
        return unit

    def update(self, instance, validated_data):
        # instance 要修改的对象
        # validated_data 校验过后的数据
        instance.name = validated_data.get('name')
        instance.conversion_relation = validated_data.get('conversion_relation')
        instance.save()  # orm的单个对象，修改了单个对象的属性，只要调用对象.save,就能把修改保存到数据库

        return instance  # 不要忘了吧修改后的对象，返回


class ProductCategorySerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField(source='category_id')

    # 序列化某些字段，这里写要序列化的字典
    # name = serializers.CharField()  # serializers下大致跟models下的类是对应的
    # description = serializers.CharField()
    # photo = serializers.CharField()
    # parent_category_id = serializers.CharField(allow_null=True)
    # team = serializers.IntegerField()
    class Meta:
        model = ProductCategory
        # fields = ['name', 'description', 'image', 'photo', 'parent_category_id', 'team']
        fields = '__all__'

    def create(self, validated_data):
        print(validated_data)
        # team_id = validated_data.pop('team', None)
        # if team_id is not None:
        #     team = Team.objects.get(pk=team_id)
        #     validated_data['team'] = team
        # 保存的逻辑
        # validated_data 校验过后的数据 {name,price,publish}
        # 保存到数据库
        product_category = ProductCategory.objects.create(**validated_data)
        # 一定不要返回新增的对象
        return product_category

    def update(self, instance, validated_data):
        # instance 要修改的对象
        # validated_data 校验过后的数据
        instance.name = validated_data.get('name')
        instance.photo = validated_data.get('photo')
        instance.description = validated_data.get('description')
        instance.parent_category_id = validated_data.get('parent_category_id')
        instance.team = validated_data.get('team')
        instance.save()  # orm的单个对象，修改了单个对象的属性，只要调用对象.save,就能把修改保存到数据库

        return instance  # 不要忘了吧修改后的对象，返回


class DishCategoryGetSerializer(serializers.ModelSerializer):
    class Meta:
        model = DishCategory
        fields = '__all__'

    def create(self, validated_data):
        print(validated_data, 1111)
        if validated_data.get('name'):
            name = validated_data.get('name')
            photo = validated_data.get('photo')
            description = validated_data.get('description')
            parent_category_id = validated_data.get('parent_category_id')
            team_id = validated_data.get('team')

            dish_category = DishCategory.objects.create(name=name,
                                                        photo=photo,
                                                        description=description,
                                                        parent_category_id=parent_category_id,
                                                        team=team_id
                                                        )
            # print(dish_category)
            # dish_category = DishCategory.objects.create(**validated_data)

            return dish_category


class InventorySerializer(serializers.ModelSerializer):
    # id = serializers.ReadOnlyField(source='record_id')  # Add this line
    class Meta:
        model = Inventory
        fields = ['record_id',
                  'product_price',
                  'product_cost_price',
                  'stock_in_time',
                  'volume',
                  'quantity',
                  'weight',
                  'stock_out_time',
                  'stock_out_quantity',
                  'procurement']


class CreateSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField(source='product_id')  # Add this line
    invent_in_db = serializers.DictField(write_only=True)

    class Meta:
        model = Product
        fields = ['id',
                  'name',
                  'description',
                  'category',
                  'photo',
                  'unit',
                  'team',
                  "invent_in_db"]

    def validate_invent_in_db(self, value):
        # Ensure product_cost_price, product_price, and quantity are present and not empty
        # if 'product_cost_price' not in value or not value['product_cost_price']:
        #     raise serializers.ValidationError("product_cost_price is required and cannot be empty.")
        if 'product_price' not in value or not value['product_price']:
            raise serializers.ValidationError("product_price is required and cannot be empty.")
        if 'quantity' not in value or not value['quantity']:
            raise serializers.ValidationError("quantity is required and cannot be empty.")

        return value

    @transaction.atomic
    def create(self, validated_data):
        inventory_data = validated_data.pop('invent_in_db')
        quantity = inventory_data.get('quantity')
        weight = inventory_data.get('weight')
        name = validated_data.get('name')
        team = validated_data.get('team')
        stock_in_time = inventory_data.get('stock_in_time')

        # 添加当前时间到 inventory_data 中
        # inventory_data['stock_in_time'] = datetime.now()
        inventory_data['stock_in_time'] = stock_in_time

        # 尝试根据 name 查找已存在的货品记录
        existing_products = Product.objects.filter(name=name).all()

        product = None
        print(existing_products)
        for existing_product in existing_products:
            if existing_product.team == team:
                # 如果找到已存在的货品记录，则使用该记录
                product = existing_product
                break
        # 否则，创建新的货品记录
        if product is None:
            product = Product.objects.create(**validated_data)
            print(inventory_data, 1111111)
            Inventory.objects.create(product=product, current_stock=weight, **inventory_data)

            return product

        # 根据货品记录的 ID 获取与该产品相关联的所有库存记录
        all_inventories = Inventory.objects.filter(product=product)

        # 输出库存记录
        for inventory in all_inventories:
            print(inventory.record_id, inventory.stock_in_time, inventory.quantity, inventory.current_stock,
                  inventory.created_at)

        # 找到离现在时间最近的库存记录
        latest_inventory = all_inventories.filter(created_at__lte=timezone.now()).order_by('-created_at').first()

        if latest_inventory:
            print(latest_inventory.record_id, latest_inventory.stock_in_time, latest_inventory.quantity,
                  latest_inventory.current_stock, latest_inventory.created_at)
            print(1111111111111111111111111111111111111111111)
            print(type(latest_inventory.current_stock), latest_inventory.current_stock)
            print(type(inventory_data.get('quantity', 0)), inventory_data.get('quantity', 0))
            print(type(inventory_data.get(
                'stock_out_quantity', 0)), inventory_data.get(
                'stock_out_quantity', 0))
            current_stock = int(latest_inventory.current_stock) + int(inventory_data.get('weight', 0)) - int(
                inventory_data.get(
                    'stock_out_quantity', 0))
        else:
            # 如果没有现有的库存记录，将 current_stock 设置为初始数量
            current_stock = inventory_data.get('weight', 0)

        # 创建一个新的库存记录，带有计算后的 current_stock
        inventory_data['current_stock'] = current_stock
        print(inventory_data)

        Inventory.objects.create(product=product, **inventory_data)

        return product


class ProductSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField(source='product_id')  # Add this line
    # inventory = InventorySerializer()
    # inventory = InventorySerializer(many=True, read_only=True, source='inventory.all')
    invent_in_db = serializers.DictField(write_only=True)
    unit_name = serializers.SerializerMethodField()
    category_name = serializers.SerializerMethodField()
    unit_type = serializers.SerializerMethodField()

    class Meta:
        model = Product
        fields = ['id',
                  'name',
                  'description',
                  'category',
                  'photo',
                  'unit',
                  'unit_name',  # 新增字段
                  'unit_type',  # 新增字段
                  'category_name',  # 新增字段
                  'team',
                  'created_at',
                  "invent_in_db"]

    def get_unit_name(self, obj):
        return obj.unit.name if obj.unit else None

    def get_unit_type(self, obj):
        return obj.unit.get_unit_type_display() if obj.unit else None

    def get_category_name(self, obj):
        return obj.category.name if obj.category else None

    def validate_invent_in_db(self, value):
        # Ensure product_cost_price, product_price, and quantity are present and not empty
        # if 'product_cost_price' not in value or not value['product_cost_price']:
        #     raise serializers.ValidationError("product_cost_price is required and cannot be empty.")
        if 'product_price' not in value or not value['product_price']:
            raise serializers.ValidationError("product_price is required and cannot be empty.")
        if 'quantity' not in value or not value['quantity']:
            raise serializers.ValidationError("quantity is required and cannot be empty.")

        return value

    @transaction.atomic
    def create(self, validated_data):
        inventory_data = validated_data.pop('invent_in_db')
        quantity = inventory_data.get('quantity')
        name = validated_data.get('name')
        team_id = inventory_data.get('team')  # 获取 team_id
        # people_created_at = validated_data.get('created_at')
        stock_in_time = inventory_data.get('stock_in_time')

        # 添加当前时间到 inventory_data 中
        # inventory_data['stock_in_time'] = datetime.now()
        inventory_data['stock_in_time'] = stock_in_time
        # 这里先检查商品表中是否存在，不存在，则在商品表中添加这个货品
        # existing_commodity = Commodity.objects.filter(name=name).first()
        # print(validated_data)
        # if not existing_commodity:
        #     # 如果商品不存在，创建一个新的商品
        #     new_commodity = Commodity.objects.create(**validated_data)  # 根据您的实际字段进行调整
        # 这里可以添加其他商品相关的属性

        # 尝试根据 name 和 team_id 查找已存在的货品记录
        existing_product = Product.objects.filter(name=name, team_id=team_id).first()

        if existing_product:
            # 如果找到已存在的货品记录，则使用该记录
            product = existing_product
        else:
            # 否则，创建新的货品记录
            product = Product.objects.create(**validated_data)
            print(inventory_data, 1111111)
            Inventory.objects.create(product=product, current_stock=quantity, **inventory_data)

            return product

        # 根据货品记录的 ID 获取与该产品相关联的所有库存记录
        all_inventories = Inventory.objects.filter(product=product)

        # 输出库存记录
        # for inventory in all_inventories:
        #     print(inventory.record_id, inventory.stock_in_time, inventory.quantity, inventory.current_stock,
        #           inventory.created_at)

        # 找到离现在时间最近的库存记录
        latest_inventory = all_inventories.filter(created_at__lte=timezone.now()).order_by('-created_at').first()

        if latest_inventory:
            print(latest_inventory.record_id, latest_inventory.stock_in_time, latest_inventory.quantity,
                  latest_inventory.current_stock, latest_inventory.created_at)
            print(1111111111111111111111111111111111111111111)
            print(type(latest_inventory.current_stock), latest_inventory.current_stock)
            print(type(inventory_data.get('quantity', 0)), inventory_data.get('quantity', 0))
            print(type(inventory_data.get(
                'stock_out_quantity', 0)), inventory_data.get(
                'stock_out_quantity', 0))
            current_stock = (int(latest_inventory.current_stock) +
                             int(inventory_data.get('quantity', 0)) -
                             int(inventory_data.get('stock_out_quantity', 0)))
        else:
            # 如果没有现有的库存记录，将 current_stock 设置为初始数量
            current_stock = inventory_data.get('quantity', 0)

        # 创建一个新的库存记录，带有计算后的 current_stock
        inventory_data['current_stock'] = current_stock
        print(inventory_data)

        Inventory.objects.create(product=product, **inventory_data)

        return product
        # return custom_response_data
        # return product

    def to_representation(self, instance):

        representation = super().to_representation(instance)

        # 获取最新的一条库存记录
        latest_inventory = instance.inventory.filter(created_at__lte=timezone.now()).order_by('-created_at').first()

        # 获取最新的一条库存有价格的
        latest_inventory_price = instance.inventory.filter(
            created_at__lte=timezone.now(),
            product_price__isnull=False  # 筛选出价格不为 null 的记录
        ).order_by('-created_at').first()

        if latest_inventory:
            try:
                product_price = latest_inventory_price.product_price
                weight = latest_inventory_price.weight
            except Exception as e:
                product_price = None
                weight = None

            # 将 weight 转换为 Decimal 类型
            # Check if weight is not None before converting
            if weight is not None:
                weight = Decimal(weight)
            # weight = Decimal(weight)

            product_cost_price = Decimal('0.0')

            # 计算成本价
            if weight:
                product_cost_price = product_price / weight
            inventory_data = {
                'record_id': latest_inventory.record_id,
                'product_price': product_price,
                'product_cost_price': product_cost_price,
                'stock_in_time': latest_inventory.stock_in_time,
                'quantity': latest_inventory.quantity,
                'weight': weight,
                'before_weight': latest_inventory.before_weight,
                'volume': latest_inventory.volume,
                "total_stock": latest_inventory.current_stock

            }
        else:
            inventory_data = {}

        representation['inventory'] = inventory_data

        return representation


class DishProductSerializer(serializers.ModelSerializer):
    # Use PrimaryKeyRelatedField to represent the existing Product
    product = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all(), write_only=True)

    class Meta:
        model = DishProduct
        fields = ['product', 'weight', 'quantity']


class DishSerializer(serializers.ModelSerializer):
    products = DishProductSerializer(many=True, write_only=True)

    class Meta:
        model = Dish
        fields = ['dish_id',
                  'name',
                  'photo',
                  'category',
                  'units',
                  'products',
                  'description',
                  'team',
                  'dish_price',
                  'dish_vip_price',
                  'category_detail',
                  'units_detail',
                  'products_list']
        extra_kwargs = {
            'description': {'max_length': 30},
            # 'dish_id': {'read_only': True},
            'products': {'write_only': True},
            'category': {'write_only': True},
            'units': {'write_only': True},
            'category_detail': {'read_only': True},
            'units_detail': {'read_only': True},
            'products_list': {'read_only': True}
        }

    def create(self, validated_data):
        products_data = validated_data.pop('products')
        print(products_data)
        dish = Dish.objects.create(**validated_data)

        for product_data in products_data:
            # Extract the product instance from the validated_data
            product_instance = product_data.pop('product')
            DishProduct.objects.create(dish=dish, product=product_instance, **product_data)

        return dish

    # 局部钩子和全局钩子跟之前完全一样
    def validate_name(self, name):
        if name.startswith('sb'):
            raise ValidationError('不能sb')

        else:
            return name

    def update(self, instance, validated_data):
        # 从 instance 中获取 ID
        dish_id = instance.dish_id

        # 现在你可以使用 dish_id 进行任何你需要的操作
        # 示例：将 ID 打印到控制台
        print("Updating Dish with ID:", dish_id)

        # 删除货品菜品对应表中和菜品 ID 相同的记录
        DishProduct.objects.filter(dish_id=dish_id).delete()
        print(validated_data)
        # 更新Dish模型的常规字段
        instance.name = validated_data.get('name')
        instance.description = validated_data.get('description', instance.description)
        instance.photo = validated_data.get('photo', instance.photo)
        instance.category = validated_data.get('category', instance.category)
        instance.units = validated_data.get('units', instance.units)
        instance.team = validated_data.get('team', instance.team)
        instance.dish_price = validated_data.get('dish_price', instance.dish_price)
        instance.dish_vip_price = validated_data.get('dish_vip_price', instance.dish_vip_price)
        instance.save()

        # 更新DishProduct模型的嵌套字段
        products_data = validated_data.pop('products', None)
        if products_data is not None:
            for product_data in products_data:
                product_instance = product_data.pop('product')
                quantity = product_data.get('quantity')
                weight = product_data.get('weight')

                # 尝试获取关联的DishProduct实例，如果不存在，则创建新的实例
                dish_product, created = DishProduct.objects.get_or_create(dish=instance,
                                                                          product=product_instance,
                                                                          quantity=quantity,
                                                                          weight=weight)

                # 如果已经存在了，则更新数量
                # if not created:
                #     dish_product.quantity = quantity
                #     dish_product.weight = weight
                #     dish_product.save()

        return instance


class ProductCategorySerializers(serializers.ModelSerializer):
    class Meta:
        model = ProductCategory
        fields = '__all__'


class UnitSerializers(serializers.ModelSerializer):
    class Meta:
        model = Unit
        fields = '__all__'


class InventorySerializers(serializers.ModelSerializer):
    class Meta:
        model = Inventory
        fields = '__all__'


class SalesRecordSerializer(serializers.ModelSerializer):
    dish_name = serializers.CharField(source='dish.name', read_only=True)

    # dish_id = serializers.IntegerField(source='dish.dish_id')

    class Meta:
        model = SalesRecord
        fields = ['record_id',
                  'dish',
                  'dish_name',
                  'sales_date',
                  'dish_price',
                  'dish_vip_price',
                  'sales_quantity',
                  'created_at',
                  'updated_at']

    def create(self, validated_data):
        print(666)
        # 如果传入的是单个字典，则直接调用父类的 create 方法
        print(validated_data)
        if isinstance(validated_data, dict):
            print(222213123)
            # 如果 validated_data 中没有传入 "sales_date" 字段，则设置为当前时间
            if 'sales_date' not in validated_data or not validated_data['sales_date']:
                validated_data['sales_date'] = datetime.now().date()
            # 处理相关的货品库存逻辑
            self.create_update_inventory(validated_data)
            return super().create(validated_data)

        # 否则，传入的是一个包含多个字典的列表
        # 初始化一个列表来存储创建的菜品销售记录
        # created_records = []
        #
        # # with transaction.atomic():
        # print(7777)
        # # 遍历接收到的字典列表
        # for record_data in validated_data:
        #     print(222)
        #     # 调用 create 方法创建菜品销售记录
        #     # instance = self.perform_create(record_data)
        #     # created_records.append(instance)
        #
        #
        #
        # return created_records

    def create_update_inventory(self, validated_data):
        # 获取销售记录中的菜品和销售数量
        dish = validated_data['dish']
        sales_quantity = validated_data['sales_quantity']

        # 获取菜品关联的所有货品信息
        dish_products = dish.dish_products.all()

        # 初始化 stock_out_quantity 变量
        stock_out_quantity = 0

        # 处理销售数量，可以根据实际情况进行逻辑处理
        for dish_product in dish_products:
            # 获取具体的货品信息
            product = dish_product.product

            # 如果产品对象存在，继续处理
            if product:

                # 尝试根据货品名称查找已存在的货品记录
                existing_product = Product.objects.filter(name=product.name).first()

                if existing_product:
                    # 如果找到已存在的货品记录，则使用该记录
                    product = existing_product
                else:
                    # 否则，创建新的货品记录
                    product = Product.objects.create(name=product.name)  # 仅作示例，具体根据模型字段调整

                # 找到关联的所有库存记录
                all_inventories = Inventory.objects.filter(product=product)

                # 获取最近的库存记录
                latest_inventory = all_inventories.filter(created_at__lte=timezone.now()).order_by(
                    '-created_at').first()

                if latest_inventory:
                    # 计算需要减去的库存数量
                    stock_out_quantity = int(sales_quantity) * int(dish_product.quantity)
                    # 更新当前库存数量
                    current_stock = int(latest_inventory.current_stock) - int(stock_out_quantity)
                    # 如果当前库存数量小于零，抛出ValidationError
                    if current_stock < 0:
                        # 获取货品名称
                        product_name = product.name
                        # 获取当前库存量
                        current_stock = latest_inventory.current_stock
                        error_message = f"货品'{product_name}'的库存量({current_stock})不足，无法完成销售。"
                        return Response({"detail": error_message}, status=status.HTTP_200_OK)
                else:
                    # 如果没有现有的库存记录，将当前库存设置为0
                    current_stock = 0

                # 创建新的库存记录
                Inventory.objects.create(
                    product=product,
                    stock_out_time=validated_data['sales_date'],  # 假设您的销售记录中有销售日期字段
                    stock_out_quantity=stock_out_quantity,
                    current_stock=current_stock
                    # 其他库存记录字段
                )

        return

    # def perform_create(self, validated_data):
    #     print(validated_data)
    #     return SalesRecord.objects.create(**validated_data)

    def update(self, instance, validated_data):
        print('数据库中的实例', instance, '传入的修改的数据', validated_data)
        # 首先，获取传入的更新数据中的销售数量
        updated_sales_quantity = validated_data.get('sales_quantity')

        # 如果销售数量没有更新，则直接调用父类的 update 方法
        if updated_sales_quantity == instance.sales_quantity:
            return super().update(instance, validated_data)

        # 否则，销售数量发生了变化，需要更新库存
        with transaction.atomic():
            # 更新相关的库存信息
            self.update_inventory(instance, updated_sales_quantity)

            # 更新销售记录
            instance = super().update(instance, validated_data)

        return instance

    def update_inventory(self, sales_record, updated_sales_quantity):
        # 获取销售记录中的菜品和销售数量
        dish = sales_record.dish
        print('修改菜品销售的菜品名字', dish)

        # 获取菜品关联的所有货品信息
        dish_products = dish.dish_products.all()
        print('菜品关联的所有货品信息', dish_products)

        # 计算销售数量的变化量
        old_sales_quantity = sales_record.sales_quantity
        sales_quantity_change = int(updated_sales_quantity) - int(old_sales_quantity)
        print('更新的销售数量', updated_sales_quantity, '数据库的销售记录', old_sales_quantity)
        print('销售数量的变化量', sales_quantity_change)

        # 处理销售数量的变化
        for dish_product in dish_products:
            # 获取具体的货品信息
            product = dish_product.product

            # 找到关联的所有库存记录
            all_inventories = Inventory.objects.filter(product=product)

            # 获取最近的库存记录
            latest_inventory = all_inventories.filter(created_at__lte=sales_record.created_at).order_by(
                '-created_at').first()

            if latest_inventory:
                stock_out_quantity_change = sales_quantity_change * int(dish_product.quantity)
                latest_inventory.current_stock = int(latest_inventory.current_stock) - stock_out_quantity_change
                latest_inventory.save()
            # else:
            #     current_stock = 0
            #     Inventory.objects.create(
            #         product=product,
            #         stock_out_time=instance.sales_date,
            #         stock_out_quantity=stock_out_quantity_change,
            #         current_stock=current_stock
            #     )

        return


class CommoditySerializer(serializers.ModelSerializer):
    # image = serializers.ImageField()  # 单独定制 image 字段
    created_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)  # 定制 created_at 字段的日期格式

    class Meta:
        model = Commodity
        fields = ['commodity_id',
                  'name',
                  'category',
                  'unit',
                  # 'image',
                  'photo',
                  'description',
                  'team',
                  'created_at',
                  ]

    def to_representation(self, instance):
        # 获取默认的序列化表示形式
        representation = super().to_representation(instance)

        # 添加额外的信息
        representation['extra_info'] = '这是额外的信息'

        # 在此添加任何其他定制
        return representation

    def validate_name(self, value):
        # Custom validation logic for the 'name' field
        if len(value) < 3:
            raise serializers.ValidationError("Name must be at least 3 characters long.")
        return value

    # Example of validate method
    def validate(self, data):
        # Custom validation logic for the entire object
        # You can access multiple fields in the 'data' dictionary
        if data['name'].lower() == 'forbidden':
            raise serializers.ValidationError("Name 'forbidden' is not allowed.")
        return data


'''
__init__: 序列化器初始化时调用的方法，可以在这里设置一些初始值。

create: 当执行保存操作时调用，用于保存新对象。

update: 当执行更新操作时调用，用于更新现有对象。

validate_<field_name>: 针对特定字段进行验证的方法。

validate: 针对整个对象进行验证的方法。

to_representation: 将模型实例或查询集转换为JSON表示时调用，可以在这里添加额外的字段或进行自定义转换。

to_internal_value: 将输入数据转换为内部表示时调用。

run_validation: 在执行验证时调用，可以添加自定义验证逻辑。
'''


class ProductSeachSerializer(serializers.ModelSerializer):
    unit_name = serializers.CharField(source='unit.name', read_only=True)
    category_name = serializers.CharField(source='category.name', read_only=True)
    unit_type = serializers.SerializerMethodField()
    latest_price = serializers.SerializerMethodField()
    latest_cost_price = serializers.SerializerMethodField()

    class Meta:
        model = Product
        fields = '__all__'

    def get_unit_type(self, obj):
        return obj.unit.get_unit_type_display() if obj.unit else None

    def get_latest_price(self, obj):
        # 检查是否存在与产品关联的 Inventory 记录
        if obj.inventory.exists():
            # 获取最近的 Inventory 记录
            latest_inventory = obj.inventory.filter(created_at__lte=datetime.now()).latest('created_at')
            return latest_inventory.product_price
        else:
            return None  # 或者返回其他适当的值

    def get_latest_cost_price(self, obj):
        # 检查是否存在与产品关联的 Inventory 记录
        if obj.inventory.exists():
            # 获取与产品关联的最近价格的逻辑
            latest_inventory = obj.inventory.filter(created_at__lte=datetime.now()).latest('created_at')
            return latest_inventory.product_cost_price if latest_inventory else None
        else:
            return None  # 或者返回其他适当的值


class DishSeachSerializer(serializers.ModelSerializer):
    unit_name = serializers.CharField(source='units.name', read_only=True)
    category_name = serializers.CharField(source='category.name', read_only=True)
    unit_type = serializers.SerializerMethodField()

    class Meta:
        model = Dish
        fields = '__all__'

    def get_unit_type(self, obj):
        return obj.units.get_unit_type_display() if obj.units else None


class ProductPurchaseSerializers(serializers.ModelSerializer):
    unit_name = serializers.CharField(source='unit.name', read_only=True)
    # unit_type = serializers.CharField(source='unit.type', read_only=True)
    category_name = serializers.CharField(source='category.name', read_only=True)
    unit_type = serializers.SerializerMethodField()

    class Meta:
        model = Product
        # fields = '__all__'  # Include all fields from the Product model
        fields = ('name', 'category', 'unit', 'team', 'unit_name', 'category_name', 'unit_type')

    def get_unit_type(self, obj):
        return obj.unit.get_unit_type_display() if obj.unit else None


class PurchaseSerializers(serializers.ModelSerializer):
    product = ProductPurchaseSerializers(read_only=True)  # Include the product data

    class Meta:
        model = Inventory
        fields = '__all__'
